package org.tinygame.herostory;

import com.google.protobuf.GeneratedMessageV3;
import com.google.protobuf.Message;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.websocketx.BinaryWebSocketFrame;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author shkstart
 * @create 2022-05-04 18:08
 */
public class GameMsgDecoder extends ChannelInboundHandlerAdapter {

    private static final Logger LOGGER= LoggerFactory.getLogger(GameMsgDecoder.class);

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if(!(msg instanceof BinaryWebSocketFrame)){
            return;
        }

        //WebSocket二进制消息会通过HttpServerCodec解码成BinaryWebSocketFrame对象
        BinaryWebSocketFrame frame=(BinaryWebSocketFrame)msg;
        ByteBuf byteBuf = frame.content();


        byteBuf.readShort();//读取消息的长度
        int msgCode = byteBuf.readShort();//读取消息的编号

        //通过消息编号，判断消息类型，构建msgBuilder
        Message.Builder msgBuilder=GameMsgRecognizer.getBuilderByMsgCode(msgCode);
        if(null==msgBuilder){
            LOGGER.error("无法识别的消息，msgCode= {} ",msgCode);
            return;
        }

        //拿到消息体
        byte[] msgBody=new byte[byteBuf.readableBytes()];
        byteBuf.readBytes(msgBody);

        //通过消息体，使用msgBuilder，完成消息的解码构建,这里clear是为了清除上一次相同msgCode时msgBuilder被放入的msgBody
        msgBuilder.clear();
        msgBuilder.mergeFrom(msgBody);
        Message newMsg=msgBuilder.build();

        if(null != newMsg){
            ctx.fireChannelRead(newMsg);
        }
    }
}
